<?php
/**
 * Description of MultipleChoiceclass
 *
 * @author Chisheng Lu, Jeffy Shih
 * @copyright Copyright(c)2010 DoRISE team, Science Education center, NTNU.
 * @since 2010-03-09
 * @version 1.0
 */
class MultipleChoice {
    //put your code here
    private $mysqli;

    function __construct() {
        //引入資料庫連結參數設定
        include '../inc/oaConn.inc.php';
        $this->mysqli = @new mysqli($mysqlHost,$mysqlUser,$mysqlPassword,$mysqlDB);
        if(mysqli_connect_errno()) {
            throw new Exception('無法建立資料庫連線！'.mysqli_connect_error());
            $this->mysqli = false;
            exit();
        }

        //連線使用編碼
        $this->mysqli->query("SET NAMES 'utf8'");
    }

    // $aryMultipleChoice: Array
    // Returns Boolean
    public function addMultipleChoice($aryMultipleChoice) {
        $bolRtn = false;
        $strNow = $this->getNowTime();
        $sql_addMC = 'INSERT INTO `MultipleChoice` (';
        $sql_values = ' VALUES(';
        if (array_key_exists('SQId', $aryMultipleChoice)) {
            $sql_addMC .= '`SQId`, ';
            $sql_values .= $aryMultipleChoice['SQId'] . ', ';
        }
        if (array_key_exists('MCOrder', $aryMultipleChoice)) {
            $sql_addMC .= '`MCOrder`, ';
            $sql_values .= $aryMultipleChoice['MCOrder'] . ', ';
        }
        if (array_key_exists('MCCorrect', $aryMultipleChoice)) {
            $sql_addMC .= '`MCCorrect`, ';
            $sql_values .= $aryMultipleChoice['MCCorrect'] . ', ';
        }
        if (array_key_exists('MCContent', $aryMultipleChoice)) {
            $sql_addMC .= '`MCContent`, ';
            $sql_values .= '\'' . $aryMultipleChoice['MCContent'] . '\', ';
        }
        if (array_key_exists('MCFileName', $aryMultipleChoice)) {
            $sql_addMC .= '`MCFileName`, ';
            $sql_values .= '\'' . $aryMultipleChoice['MCFileName'] . '\', ';
        }
        if (array_key_exists('UserId', $aryMultipleChoice)) {
            $sql_addMC .= '`UserId`, ';
            $sql_values .= $aryMultipleChoice['UserId'] . ', ';
        }
        $sql_addMC .= '`MCCreated`, ';
        $sql_values .= '\'' . $strNow . '\', ';
        $sql_addMC .= '`MCModified` ';
        $sql_values .= '\'' . $strNow . '\') ';
        $sql_addMC .= ')' . $sql_values . ';';
        $rs_addMC = $this->mysqli->query($sql_addMC);
        if (!$rs_addMC) {
            throw new Exception('新增選擇答案資料時發生錯誤！');
        }else {
            $bolRtn = true;
        }
        return $bolRtn;

    }

    // $intMCId: int
    // $aryMultipleChoice: Array
    // Returns Boolean
    public function editMultipleChoice($intMCId, $aryMultipleChoice) {
        //檢查題幹編號是否為空白
        if (empty ($intMCId)) {
            throw new Exception('缺少選擇答案編號！');
        }
        $bolRtn = false;
        $strNow = $this->getNowTime();
        $sql_editMC = 'Update MultipleChoice set ';
        if (array_key_exists('SQId', $aryMultipleChoice))
            $sql_editMC .= 'SQId = ' . $aryMultipleChoice['SQId'] . ', ';
        if (array_key_exists('MCOrder', $aryMultipleChoice))
            $sql_editMC .= 'MCOrder = ' . $aryMultipleChoice['MCOrder'] . ', ';
        if (array_key_exists('MCCorrect', $aryMultipleChoice))
            $sql_editMC .= 'MCCorrect = ' . $aryMultipleChoice['MCCorrect'] . ', ';
        if (array_key_exists('MCContent', $aryMultipleChoice))
            $sql_editMC .= 'MCContent = \'' . $aryMultipleChoice['MCContent'] . '\', ';
        if (array_key_exists('MCFilePath', $aryMultipleChoice))
            $sql_editMC .= 'MCFilePath = \'' . $aryMultipleChoice['MCFilePath'] . '\', ';
        if (array_key_exists('UserId', $aryMultipleChoice))
            $sql_editMC .= 'UserId = ' . $aryMultipleChoice['UserId'] . ', ';
        $sql_editMC .= 'MCModified = \'' . $strNow . '\' ';
        $sql_editMC .= 'where MCId = ' . $intMCId . ';';
        $rs_editMC = $this->mysqli->query($sql_editMC);
        if (!$rs_editMC) {
            throw new Exception('更新選擇答案資料時發生錯誤！');
        }else {
            $bolRtn = true;
        }
        return $bolRtn;
    }

    // $intMCId: int
    // Returns Boolean
    public function delMultipleChoiceByMCId($intMCId) {
        $bolRtn = false;
        //檢查選擇答案編號是否為空白
        if (empty ($intMCId)) {
            throw new Exception('缺少選擇答案項目編號。');
        }

        $intSQId = $this->getMultipleChoiceSQIdByMCId($intMCId);

        if($intSQId == 0) {
            throw new Exception('指定的編號項目內容不存在！');
        }
        //取得單選項目的檔案名稱作為刪除檔案用
        $aryMCItemInfo = $this->getMultipleChoiceInfoByMCId($intMCId);
        $strFileName = $aryMCItemInfo[5];

        //檔案名稱不為空白，則刪除上傳已儲存的圖檔
        if(!empty($strFileName)) {
            //刪除上傳原始圖檔
            $strOrigImg = _APP_PATH . "uploadfiles/" . $strFileName;
            if(file_exists($strOrigImg)) {
                if(!unlink($strOrigImg)) {
                    throw new Exception('刪除上傳原始圖檔失敗');
                }
            }

            //刪除重製圖檔
            $strRebuildImg = _APP_PATH . "uploadfiles/saved/" . $strFileName;
            if(file_exists($strRebuildImg)) {
                if(!unlink($strRebuildImg)) {
                    throw new Exception('刪除上傳的重製圖檔失敗');
                }
            }

            //刪除重製的縮圖
            $strThumbImg = _APP_PATH . "uploadfiles/saved/thumb/" . $strFileName;
            if(file_exists($strThumbImg)) {
                if(!unlink($strThumbImg)) {
                    throw new Exception('刪除上傳的重製縮圖失敗');
                }
            }
        }
        //刪除資料庫中的資料
        $sql_delMC = 'DELETE FROM `MultipleChoice` WHERE `MCId`=' . $intMCId;
        $rs_delMC = $this->mysqli->query($sql_delMC);
        if (!$rs_delMC) {
            throw new Exception('錯誤！刪除選擇答案時發生錯誤。');
        }else {
            $this->setReSortOrderBySQId($intSQId);
            $bolRtn = true;
        }



        return $bolRtn;

    }

    public function delMultipleChoiceBySQId($intSQId) {
        $bolRtn = false;
        if(empty ($intSQId)) {
            throw new Exception('缺少子題編號，無法刪除單選選項。');
        }
        //刪除項目
        $sql_delMC = 'DELETE FROM `MultipleChoice` WHERE `SQId`=' . $intSQId;
        $rs_delMC = $this->mysqli->query($sql_delMC);
        if (!$rs_delMC) {
            throw new Exception('錯誤！刪除單選選項時發生錯誤。');
        }else {
            $bolRtn = true;
        }

        return $bolRtn;
    }

    // $intMCId: int
    // Returns Array
    public function getMultipleChoiceInfoByMCId($intMCId) {
        //檢查選擇答案編號是否為空白
        if (empty ($intMCId)) {
            throw new Exception('缺少選擇答案編號！');
        }

        $sql_getMCById = 'SELECT * FROM `MultipleChoice` WHERE `MCId`=' . $intMCId;
        $rs_getMCById = $this->mysqli->query($sql_getMCById);

        if (!$rs_getMCById) {
            throw new Exception('無法查詢該選擇答案的資料！');
        }else {
            if ($rs_getMCById->num_rows == 0) {
                throw new Exception('無此選擇答案編號的資料！');
            }else {
                $row_getMCById = $rs_getMCById->fetch_row();
                return $row_getMCById;
            }
        } //End If

    }

    // Returns Array
    public function getMultipleChoiceListBySQId($intSQId) {
        $sql_getMCList = 'SELECT * FROM `MultipleChoice` WHERE `SQId`=' . $intSQId . ' ORDER BY `MCOrder`';
        $rs_getMCList = $this->mysqli->query($sql_getMCList);

        if (!$rs_getMCList) {
            throw new Exception('無法查詢該選擇答案的資料！');
        }else {
            $aryMCList = array();
            while ($aryOneMC = $rs_getMCList->fetch_row()) {
                array_push($aryMCList, $aryOneMC);
            }
            return $aryMCList;
        } //End If

    }

    public function setMCCorrectAnswerByMCId($intMCId) {
        $bolRtn = false;
        if(empty ($intMCId)) {
            throw new Exception('答案編號為空值，無法設定！');
        }

        $intSQId = $this->getMultipleChoiceSQIdByMCId($intMCId);

        if($intSQId == 0) {
            throw new Exception('無法依單選選項編號查詢子題編號！');
        }

        //先將同子題的答案都設為0
        $sql_setDefaultZero = 'UPDATE `MultipleChoice` SET `MCCorrect`=0 WHERE `SQId`=' . $intSQId;
        if(!$this->mysqli->query($sql_setDefaultZero)) {
            throw new Exception('無法將所有正確答案標記都設定為零！');
        }

        $sql_setCorrectAnswer = 'UPDATE `MultipleChoice` SET `MCCorrect`=1 WHERE `MCId`=' . $intMCId;
        if($this->mysqli->query($sql_setCorrectAnswer)) {
            $bolRtn = true;
        }

        return $bolRtn;
    }

    private function setReSortOrderBySQId($intSQId) {
        if(empty ($intSQId)) {
            throw new Exception('缺少子題編號');
        }

        $sql_getMCIdBySQId = 'SELECT `MCId` FROM `MultipleChoice` WHERE `SQId`=' . $intSQId . ' ORDER BY `MCOrder`';
        $rs_getMCIdBySQId = $this->mysqli->query($sql_getMCIdBySQId);
        if(!$rs_getMCIdBySQId) {
            throw new Exception('查詢單選答案編號時發生錯誤！');
        }

        $aryMCId = array();
        while($row_getMCIdBySQId = $rs_getMCIdBySQId->fetch_row()) {
            array_push($aryMCId, $row_getMCIdBySQId[0]);
        }

        $intCountOrder = 1;
        foreach($aryMCId as $rowMCId) {
            $sql_setNewOrder = 'UPDATE `MultipleChoice` SET `MCOrder`=' . $intCountOrder . ' WHERE `MCId`=' . $rowMCId;
            if(!$this->mysqli->query($sql_setNewOrder)) {
                throw new Exception('更新答案順位時發生錯誤，MCId=' . $rowMCId);
            }
            $intCountOrder++;
        }

        return true;
    }

    private function getNowTime() {
        return date('Y-m-d H:i:s');
    }

    public function getMultipleChoiceSQIdByMCId($intMCId) {
        $intSQId = 0;
        //檢查選擇答案編號是否為空白
        if (empty ($intMCId)) {
            throw new Exception('錯誤！缺少選擇答案編號。');
        }

        //查詢答案所屬子題編號
        $sql_GetSQId = 'SELECT `SQId` FROM `MultipleChoice` WHERE `MCId`=' . $intMCId;
        $rs_GetSQId = $this->mysqli->query($sql_GetSQId);
        $row_GetSQId = $rs_GetSQId->fetch_row();
        $intSQId = $row_GetSQId[0];

        return $intSQId;
    }

    function  __destruct() {
        if ($this->mysqli) {
            $this->mysqli->close();
            $this->mysqli = FALSE;
        }
    }
}
?>
